package pin

import (
	"fmt"
	"io"
	"strings"
)

func (p *Pin) PinNumber() int {
	return p.number
}

// Read the current value of the pin.
func (p *Pin) Read() (Value, error) {
	// seek to beginning of file in case we've read it before
	if _, err := p.value.Seek(0, 0); err != nil {
		return LOW, err
	}

	d, err := io.ReadAll(p.value)
	if err != nil {
		return LOW, err
	}
	value := strings.TrimSpace(string(d))
	switch value {
	case "0":
		return LOW, nil
	case "1":
		return HIGH, nil
	default:
		return 0, fmt.Errorf("unrecognized value '%s'", value)
	}
}

// Set the current value of the pin.
func (p *Pin) Write(value Value) error {
	var data []byte
	switch value {
	case LOW:
		data = []byte("0\n")
	case HIGH:
		data = []byte("1\n")
	}
	_, err := p.value.Write(data)
	return err
}

// Close the pin.
func (p *Pin) Close() error {
	if err := p.value.Close(); err != nil {
		return err
	}
	if err := setPinExport(p.number, false); err != nil {
		return err
	}
	return nil
}
